﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy;
using TracyGUI.UIComponent;
using Tracy.DataModel;
using System.Windows.Forms;
using Tracy.Messages;
using Tracy.Handlers;
using SharedLib.MessageFramework;

namespace TracyGUI
{
    public partial class FormMain
    {
        FormSelection<ListBoxItemResource> _formNewResourceSelection;

        private void InitResources()
        {
            _formNewResourceSelection = new FormSelection<ListBoxItemResource>("New Resource Found", "The following new resources are detected, do you want to download them now?", false);
            _formNewResourceSelection.SelectionConfirmed += new EventHandler<GenericEventArgs<List<ListBoxItemResource>>>(FoundNewResource_SelectionConfirmed);
        }

        /// <summary>
        /// Add new resource tab if not exist
        /// </summary>
        /// <param name="entryName">'All' - All Resources; 'New' - New Resources; Otherwise - Entry ID</param>
        private void AddResourcesTab(string entryName, TabControl container, string parameter = null)
        {

            TabPageResources newTab = new TabPageResources(TabPageEntry.TABPAGE_NAME_RESOURCES, TabPageEntry.TABPAGE_NAME_RESOURCES, contextMenuStripResource);
            LoadDataToResourceTab(newTab, entryName, parameter);
            container.TabPages.Add(newTab);
        }

        private void LoadDataToResourceTab(TabPageResources tab, string entryName, string parameter = null, bool clearView = true)
        {
            if (entryName == TabPageEntry.TABPAGE_NAME_ALL)
            {
                tab.LoadDataItemsToListView(TracyFacade.Instance.ResourceProvider.GetItems(), clearView);
            }
            else if (entryName == TabPageEntry.TABPAGE_NAME_SEARCH)
            {
                tab.LoadDataItemsToListView(TracyFacade.Instance.SearchEngine.ResourceSearchResult, clearView);
            }
            else
            {
                Entry entry = TracyFacade.Instance.EntryProvider.GetItemByID(entryName);
                tab.LoadDataItemsToListView(TracyFacade.Instance.ResourceProvider.GetItemByEntry(entry), clearView);
            }
        }

        private void AddNewResource(Resource res)
        {
            if (res != null && res.Entry != null)
            {
                res.Created = System.DateTime.Today.ToString();
                TracyFacade.Instance.ResourceProvider.AddItem(res);
                string resEntryID = res.Entry.ID;
                foreach (TabPageEntry tabPage in GetRelatedEntryTabs(resEntryID))
                {
                    (tabPage.GetTabPage(TabPageEntry.TABPAGE_NAME_RESOURCES) as TabPageResources).AddDataItemToListView(res);
                }
            }
        }

        private void downloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DownloadSelectedResources();
        }

        private List<Resource> GetSelectedResources()
        {
            TabPageEntry entryTab = _tabControlContent.SelectedTab as TabPageEntry;
            TabPageResources resTab = entryTab.GetTabPage(TabPageEntry.TABPAGE_NAME_RESOURCES) as TabPageResources;
            if (resTab != null)
            {
                return resTab.GetSelectedDataItems();
            }
            return new List<Resource>();
        }

        private void removeResourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPageEntry entryTab = _tabControlContent.SelectedTab as TabPageEntry;
            TabPageResources resTab = entryTab.GetTabPage(TabPageEntry.TABPAGE_NAME_RESOURCES) as TabPageResources;
            if (resTab != null)
            {
                List<Resource> resourcesToRemove = resTab.GetSelectedDataItems();
                resTab.RemoveDataItems(resourcesToRemove);
                RemoveResourcesAction(resourcesToRemove);
            }
        }

        //TODO: Move to controller, separate it from UI logic
        private void RemoveResourcesAction(List<Resource> resourcesToRemove)
        {

            List<MediaFile> filesToRemove = new List<MediaFile>();
            foreach (Resource res in resourcesToRemove)
            {
                filesToRemove.AddRange(TracyFacade.Instance.MediaFileProvider.GetItemByResource(res));
            }

            RemoveMediaFilesAction(filesToRemove);
            foreach (Resource res in resourcesToRemove)
            {
                TracyFacade.Instance.ResourceProvider.RemoveItem(res.ID);
            }
        }



        private void DownloadSelectedResources()
        {

            foreach (Resource res in GetSelectedResources())
            {
                SendResourceToDownload(res);
            }

        }

        private void SendResourceToDownload(Resource res)
        {
            if (res != null && _mappingEntry.ContainsKey(res.Entry.ID))
            {
                TracyFacade.Instance.MessageDispatcher.EnqueueMessage(new TaskMessage(this, typeof(StartDownloadHandler), res, new MessageCallback(OnResourceSentToDownloader)));
                TracyFacade.Instance.MessageDispatcher.EnqueueMessage(new TaskMessage(this, typeof(AssignMediaFileHandler), res, new MessageCallback(OnResourceMediaFilesAssigned)));
            }
        }

        private void OnResourceSentToDownloader(IAppMessage msg)
        {
            
            Resource res = msg.Data as Resource;
            ChangeResourceStatus(res, "Sent");
        }

        private void ChangeResourceStatus(Resource res, string newStatus)
        {
            if (res != null)
            {
                res.Status = newStatus;
                TracyFacade.Instance.ResourceProvider.UpdateItem(res);
                foreach (TabPageEntry entryTab in GetRelatedEntryTabs(res.Entry.ID))
                {
                    TabPageResources resTab = entryTab.GetTabPage(TabPageEntry.TABPAGE_NAME_RESOURCES) as TabPageResources;
                    if (resTab != null)
                    {
                        resTab.UpdateDataItem(res);
                    }
                }
            }
        }

        #region auto download mode
        private bool IsAutoDownloadMode
        {
            get { return TracyFacade.Instance.DownloadManager.IsAutoDownloadMode; }
            set
            {
                TracyFacade.Instance.DownloadManager.IsAutoDownloadMode = value;
                if (value)
                {
                    toolStripButtonAutoMode.Text = "On";
                }
                else
                {
                    toolStripButtonAutoMode.Text = "Off";
                }
            }
        }
        private void toolStripButtonAutoMode_Click(object sender, EventArgs e)
        {
            IsAutoDownloadMode = !IsAutoDownloadMode;
        }
        #endregion
    }
}
